package top.infopub.mgr.mkt.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.dao.BidOpenResultDao;
import top.infopub.mgr.mkt.domain.BidSubsidyDomain;
import top.infopub.mgr.mkt.jsonvo.AfterSummaryJsonVo;
import top.infopub.mgr.mkt.service.BidSubsidyService;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.BidSubsidyVo;
import top.infopub.mgr.mkt.vo.DiscloseProVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.*;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 投标补贴申请
 * @author Awoke
 * @version 2020年3月25日
 * @see BidSubsidyController
 * @since
 */
@Controller
@RequestMapping("/bidSubsidy")
public class BidSubsidyController extends GenericFlowController {

    @Autowired
    private BidOpenResultDao bidOpenResultDao;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private BidSubsidyService bidSubsidyService;

    @Autowired
    private ProProcessManageService proProcessManageService;
    /**
     * list页面
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "mkt/lay-bidSubsidy-list";
    }

    /**
     * 投标补贴申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<BidSubsidyDomain> queryDataByCondition(BidSubsidyVo bidSubsidyVo,
                                                        ParamPage paramPage) throws ParseException {
        Page<BidSubsidyDomain> page = new Page<BidSubsidyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
//        if (bidSubsidyVo.getEndDate() != null) {
//            bidSubsidyVo.setEndDate(DateUtils.addDays(bidSubsidyVo.getEndDate(), 1));
//        }
        page = bidSubsidyService.selectByDomainWhere(page, bidSubsidyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 投标补贴申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<BidSubsidyDomain> queryMyCheckDataByCondition(BidSubsidyVo bidSubsidyVo,
                                                               ParamPage paramPage) {
        Page<BidSubsidyDomain> page = new Page<BidSubsidyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
//        if (bidSubsidyVo.getEndDate() != null) {
//            bidSubsidyVo.setEndDate(DateUtils.addDays(bidSubsidyVo.getEndDate(), 1));
//        }
        bidSubsidyVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = bidSubsidyService.selectMyCheckByDomainWhere(page, bidSubsidyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }



    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询已交底的记录
        DisclosePro disclosePro = new DisclosePro();
        disclosePro.setProcessStatus("9");
        List<DisclosePro> disclosePros = discloseProService.selectByEntityWhere(disclosePro);
        request.setAttribute("disclosePros", disclosePros);
        return "mkt/lay-bidSubsidy-add";
    }

    /**
     * 根据id查询投标补贴申请详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 投标补贴申请Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request, String id, String proCode) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id",id);
        BidSubsidy bidSubsidy = bidSubsidyService.selectByPrimaryKey(id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        if (bidSubsidy != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidSubsidy.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), bidSubsidy.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(bidSubsidy.getProcessId()) && bidSubsidy.getProcessId().length() > 10) {
                request.setAttribute("processId", bidSubsidy.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(bidSubsidy.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidSubsidy.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        request.setAttribute("proCode",proCode);
        return "mkt/lay-tenderSubsidy-detail";
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //开标结果审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }

    /***** 详情 ******/
    @RequestMapping("/queryDetailById")
    @ResponseBody
    public RspVo queryDetailById(String id) {
        AfterSummaryJsonVo afterSummJson = bidSubsidyService.queryDetailById(id);
        return RspVo.getSuccessResponse(afterSummJson);
    }


    /***保存**/
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String bodyStr,Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        AfterSummaryJsonVo aftSummJson = JSON.parseObject(str, AfterSummaryJsonVo.class);
        BidSubsidy subsidy = aftSummJson.getSubsidy();
        subsidy.setUptBy(vo.getId());
        subsidy.setProCode(aftSummJson.getInfo().getProCode());
        /**
         * 附件处理
         * */
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(aftSummJson.getFileAtt()!=null){
            String[] fileAtt = aftSummJson.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo,aftSummJson.getInfo().getProCode(),file);
                attachmentList.add(attachment);
            }
        }
        String id = aftSummJson.getId();
        if (StringUtils.isEmpty(id))
        {
            //id为空 保存新增的数据
            bidSubsidyService.insertById(subsidy, attachmentList, submitType, bodyStr, vo,aftSummJson);
        }else {
            //更新信息
            bidSubsidyService.updateById(subsidy, attachmentList, submitType, bodyStr, vo);
        }
        return RspVo.getSuccessResponse();
    }

    /**
     * 新增投标补贴申请
     * @return
     */
//    @SuppressWarnings({"rawtypes"})
//    @RequestMapping("/save")
//    public @ResponseBody RspVo save(BidSubsidyAssist bidSubsidyAssist) {
//
//        //投标补贴申请表处理
//        bidSubsidyAssist.setHrDeptId(bidSubsidyAssist.getHrDeptid());
//        bidSubsidyAssist.setHrOrgId(bidSubsidyAssist.getHrOrgid());
//        bidSubsidyAssist.setStaffName(bidSubsidyAssist.getStaffname());
//        bidSubsidyAssist.setHrStaffApplyId(bidSubsidyAssist.getHrStaffApplyid());
//        String proCodeAndCodes = bidSubsidyAssist.getProCodeAndCodes();
//        String[] split = proCodeAndCodes.split("\\_");
//        bidSubsidyAssist.setProCode(split[0]);
//        bidSubsidyAssist.setProName(split[2]);
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = IdFactory.getUUIDUpper();
//        bidSubsidyAssist.setId(id);
//        bidSubsidyAssist.setSgCityId(split[3]);
//        bidSubsidyAssist.setAddBy(vo.getId());
//        bidSubsidyAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String code = codeGeneratorConfigService.generatorCode("mkt_bid_subsidy");
//        bidSubsidyAssist.setCodes(code);
//        // 处理processId
//        bidSubsidyAssist.setProcessId(IdFactory.getUUIDUpper());
//        bidSubsidyAssist.setProcessStatus("1");//审批中
//        bidSubsidyAssist.setUptBy(vo.getId());
//        bidSubsidyAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //上传附件
//        List<BidSubsidyAtt> bidSubsidyAtts = new ArrayList<BidSubsidyAtt>();
//        //其他附件
//        String[] fileAtts1 = bidSubsidyAssist.getFileAtts1();
//        if (fileAtts1 != null) {
//            for (String file : fileAtts1) {
//                BidSubsidyAtt bidSubsidyAtt = createFileAtt(vo, id, file);
//                bidSubsidyAtts.add(bidSubsidyAtt);
//            }
//        }
//        bidSubsidyService.saveBidSubsidy(bidSubsidyAssist, bidSubsidyAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "市场管理 -付款申请-投标补贴申请：项目名="
//                                                              + bidSubsidyAssist.getProName(),
//            null);
//        return RspVo.getSuccessResponse();
//    }

    private BidSubsidyAtt createFileAtt(AuthorizationVO vo, String subsidyId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        BidSubsidyAtt fileAtt = new BidSubsidyAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setSubsidyId(subsidyId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 根据id查询交底记录
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBidSubsidyById")
    @ResponseBody
    public Map<String, Object> getBidSubsidyById(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String[] split = proCodeAndCodes.split("\\_");
            DiscloseProVo discloseProVo = discloseProService.selectById(split[1]);
            map.put("discloseProVo", discloseProVo);
        }
        catch (Exception e) {
            log.error("查询交底记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }



    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "bidSubsidyAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
    //投标补贴新增按钮后可选的项目名称
    @RequestMapping("/optionalProjectName")
    @ResponseBody
    public List<ProjectInfo> optionalProjectName()
    {       //呆呆姐说要用开标结果的列表的project的PROCODE
        List<ProjectInfo> list =  bidSubsidyService.optionalProjectName();

        return list;
    }
    //投标补贴新增按钮后可选的项目名称查询出来的数据
    @RequestMapping("/selectProjectById")
    @ResponseBody
    public ProjectInfo selectProjectById(String proCode)
    {
        ProjectInfo projectInfo =  bidSubsidyService.selectProjectById(proCode);
        return projectInfo;
    }
}
